"""
邮件发送任务模型
"""
from sqlalchemy import Column, Integer, String, Boolean, Text, ForeignKey, DateTime, JSON, Enum as SQLEnum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base
import enum


class EmailTaskStatus(enum.Enum):
    """邮件任务状态枚举"""
    PENDING = "pending"      # 等待中
    RUNNING = "running"      # 发送中
    COMPLETED = "completed"  # 已完成
    FAILED = "failed"        # 失败
    CANCELLED = "cancelled"  # 已取消


class EmailSendMode(enum.Enum):
    """邮件发送模式枚举"""
    BATCH = "batch"                    # 批量发送（相同内容）
    PERSONALIZED = "personalized"     # 个性化发送（不同内容）


class EmailTask(Base):
    """邮件发送任务模型"""
    __tablename__ = "email_tasks"

    id = Column(String(36), primary_key=True, index=True, comment="任务ID")
    subject = Column(String(500), nullable=False, comment="邮件主题")
    content = Column(Text, nullable=False, comment="邮件内容")
    template_id = Column(Integer, ForeignKey("email_templates.id"), nullable=True, comment="模板ID")
    email_config_id = Column(Integer, ForeignKey("email_configs.id"), nullable=False, comment="邮件配置ID")
    data_source_id = Column(Integer, ForeignKey("data_sources.id"), nullable=True, comment="数据源ID")

    # 发送配置
    send_mode = Column(SQLEnum(EmailSendMode), nullable=False, default=EmailSendMode.BATCH, comment="发送模式")
    send_immediately = Column(Boolean, default=True, comment="是否立即发送")
    scheduled_time = Column(DateTime(timezone=True), nullable=True, comment="定时发送时间")

    # 收件人配置
    recipients_config = Column(JSON, comment="收件人配置")
    template_variables = Column(JSON, comment="模板变量")
    attachments = Column(JSON, comment="附件信息")

    # 统计信息
    recipients_count = Column(Integer, default=0, comment="收件人总数")
    sent_count = Column(Integer, default=0, comment="发送成功数")
    failed_count = Column(Integer, default=0, comment="发送失败数")

    # 任务状态
    status = Column(SQLEnum(EmailTaskStatus), nullable=False, default=EmailTaskStatus.PENDING, comment="任务状态")
    error_message = Column(Text, comment="错误信息")

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    started_at = Column(DateTime(timezone=True), nullable=True, comment="开始时间")
    completed_at = Column(DateTime(timezone=True), nullable=True, comment="完成时间")

    # 用户关联
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")

    # 关系
    user = relationship("User", back_populates="email_tasks")
    template = relationship("EmailTemplate")
    email_config = relationship("EmailConfig")
    data_source = relationship("DataSource")
    send_records = relationship("EmailSendRecord", back_populates="task", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<EmailTask(id='{self.id}', subject='{self.subject}', status='{self.status}')>"


class EmailSendStatus(enum.Enum):
    """邮件发送状态枚举"""
    PENDING = "pending"    # 等待发送
    SENT = "sent"         # 发送成功
    FAILED = "failed"     # 发送失败
    BOUNCED = "bounced"   # 邮件退回


class EmailSendRecord(Base):
    """邮件发送记录模型"""
    __tablename__ = "email_send_records"

    id = Column(String(36), primary_key=True, index=True, comment="记录ID")
    task_id = Column(String(36), ForeignKey("email_tasks.id"), nullable=False, comment="任务ID")

    # 收件人信息
    recipient_email = Column(String(255), nullable=False, comment="收件人邮箱")
    recipient_name = Column(String(255), comment="收件人姓名")

    # 邮件内容
    rendered_subject = Column(String(500), comment="渲染后的主题")
    rendered_content = Column(Text, comment="渲染后的内容")
    recipient_variables = Column(JSON, comment="收件人变量")

    # 发送状态
    status = Column(SQLEnum(EmailSendStatus), nullable=False, default=EmailSendStatus.PENDING, comment="发送状态")
    sent_at = Column(DateTime(timezone=True), nullable=True, comment="发送时间")
    error_message = Column(Text, comment="错误信息")
    message_id = Column(String(255), comment="邮件消息ID")

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关系
    task = relationship("EmailTask", back_populates="send_records")

    def __repr__(self):
        return f"<EmailSendRecord(id='{self.id}', email='{self.recipient_email}', status='{self.status}')>"
